from fastapi import FastAPI, HTTPException, Depends
from sqlalchemy import create_engine, Column, Integer, String, Text, ForeignKey, TIMESTAMP
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from pydantic import BaseModel
from typing import List
import mysql.connector

# 数据库连接
DATABASE_URL = "mysql+mysqlconnector://root:123456@localhost/clinic"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

# 数据模型
class Doctor(Base):
    __tablename__ = "doctors"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    specialty = Column(String(100))
    phone = Column(String(20))

class Patient(Base):
    __tablename__ = "patients"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    age = Column(Integer)
    gender = Column(String(10))
    contact = Column(String(20))

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, nullable=False)
    password = Column(String(100), nullable=False)
    role = Column(String(50))

class MedicalRecord(Base):
    __tablename__ = "medical_records"
    id = Column(Integer, primary_key=True, index=True)
    patient_id = Column(Integer, ForeignKey("patients.id"))
    doctor_id = Column(Integer, ForeignKey("doctors.id"))
    diagnosis = Column(Text)
    treatment = Column(Text)
    date = Column(TIMESTAMP, default=datetime.now)

class Medication(Base):
    __tablename__ = "medications"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False)
    description = Column(Text)
    stock = Column(Integer)

class AppointmentQueue(Base):
    __tablename__ = "appointment_queue"
    id = Column(Integer, primary_key=True, index=True)
    patient_id = Column(Integer, ForeignKey("patients.id"))
    doctor_id = Column(Integer, ForeignKey("doctors.id"))
    status = Column(String(50), default="waiting")
    timestamp = Column(TIMESTAMP, default=datetime.now)

# Pydantic 模型
class DoctorCreate(BaseModel):
    name: str
    specialty: str
    phone: str

class PatientCreate(BaseModel):
    name: str
    age: int
    gender: str
    contact: str

class UserCreate(BaseModel):
    username: str
    password: str
    role: str

class MedicalRecordCreate(BaseModel):
    patient_id: int
    doctor_id: int
    diagnosis: str
    treatment: str

class MedicationCreate(BaseModel):
    name: str
    description: str
    stock: int

class AppointmentQueueCreate(BaseModel):
    patient_id: int
    doctor_id: int

# 数据库初始化
Base.metadata.create_all(bind=engine)

# FastAPI 应用
app = FastAPI()

# 数据库依赖
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# 医生接口
@app.post("/doctors/", response_model=DoctorCreate)
def create_doctor(doctor: DoctorCreate, db: Session = Depends(get_db)):
    db_doctor = Doctor(**doctor.dict())
    db.add(db_doctor)
    db.commit()
    db.refresh(db_doctor)
    return db_doctor

@app.get("/doctors/", response_model=List[DoctorCreate])
def get_doctors(db: Session = Depends(get_db)):
    return db.query(Doctor).all()

# 病人接口
@app.post("/patients/", response_model=PatientCreate)
def create_patient(patient: PatientCreate, db: Session = Depends(get_db)):
    db_patient = Patient(**patient.dict())
    db.add(db_patient)
    db.commit()
    db.refresh(db_patient)
    return db_patient

@app.get("/patients/", response_model=List[PatientCreate])
def get_patients(db: Session = Depends(get_db)):
    return db.query(Patient).all()

# 系统用户接口
@app.post("/users/", response_model=UserCreate)
def create_user(user: UserCreate, db: Session = Depends(get_db)):
    db_user = User(**user.dict())
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

@app.get("/users/", response_model=List[UserCreate])
def get_users(db: Session = Depends(get_db)):
    return db.query(User).all()

# 病历接口
@app.post("/medical_records/", response_model=MedicalRecordCreate)
def create_medical_record(record: MedicalRecordCreate, db: Session = Depends(get_db)):
    db_record = MedicalRecord(**record.dict())
    db.add(db_record)
    db.commit()
    db.refresh(db_record)
    return db_record

@app.get("/medical_records/", response_model=List[MedicalRecordCreate])
def get_medical_records(db: Session = Depends(get_db)):
    return db.query(MedicalRecord).all()

# 药物信息接口
@app.post("/medications/", response_model=MedicationCreate)
def create_medication(medication: MedicationCreate, db: Session = Depends(get_db)):
    db_medication = Medication(**medication.dict())
    db.add(db_medication)
    db.commit()
    db.refresh(db_medication)
    return db_medication

@app.get("/medications/", response_model=List[MedicationCreate])
def get_medications(db: Session = Depends(get_db)):
    return db.query(Medication).all()

# 就诊队列接口
@app.post("/appointment_queue/", response_model=AppointmentQueueCreate)
def create_appointment(appointment: AppointmentQueueCreate, db: Session = Depends(get_db)):
    db_appointment = AppointmentQueue(**appointment.dict())
    db.add(db_appointment)
    db.commit()
    db.refresh(db_appointment)
    return db_appointment

@app.get("/appointment_queue/", response_model=List[AppointmentQueueCreate])
def get_appointments(db: Session = Depends(get_db)):
    return db.query(AppointmentQueue).all()